const app = getApp()
import {add,getCount} from "../../utils/db";
// 在页面中定义插屏广告
let interstitialAd = null
import config from "../../utils/config";
 Page({
	data: {
		hiddenName: false,
		avatarUrl: "/images/user-unlogin.png",
		userInfo: {},
		logged: false,
		requestResult: "",
		history: [], //   用户的播放历史
		appName:config.appName,
		isAd:config.isAd
	},
	//跳转到详情页
	toDetail(e) {
		var id = e.currentTarget.id;
		wx.navigateTo({
			url: `/pages/detail/detail?id=${id}`,
			success: (res) => {},
		});
	},
	onLoad() {
		// 在页面onLoad回调事件中创建插屏广告实例
		if (wx.createInterstitialAd) {
			interstitialAd = wx.createInterstitialAd({
				adUnitId: 'adunit-c41d7d7535a297d5'
			})
			interstitialAd.onLoad(() => {})
			interstitialAd.onError((err) => {})
			interstitialAd.onClose(() => {})
		}

		var userInfo = app.globalData.userInfo;
		if (userInfo == undefined) {
			//没有获取到用户信息
			app.getUserInfo = (res) => {
				this.setData({
					userInfo: res.userInfo,
					logged: true
				})
			}

		} else {
			//获取到用户信息
			this.setData({
				userInfo: userInfo,
				logged: true
			})
		}
	},
	//页面加载的时候获取播放记录
	onShow() {
		// 在适合的场景显示插屏广告
		if (interstitialAd) {
		  interstitialAd.show().catch((err) => {
		    console.error(err)
		  })
		}
		
		this.getPlayHistory();
		this.setData({
			userInfo: app.globalData.userInfo,
			// isShow: app.globalData.isShow,
		});
	},
	//用户同意获取个人信息
	async onGetUserInfo(e){
		//如果用户拒绝，直接return掉
		var userInfo=e.detail.userInfo;
		if(userInfo==undefined)return;
		//如果用户同意，获取用户信息，保存到数据库
		app.globalData.userInfo = userInfo;

		//把结果渲染到页面
		this.setData({
			logged: true,
			userInfo: e.detail.userInfo,
		});

		//把用户信息添加到数据库
		var openid=wx.getStorageSync('openid')
		var result=await getCount("users",{_openid:openid}).catch(err=>{
			console.error(err)
		})
		if(result.total>0)return;
		var addtime=new Date().getTime()
		var result =await add("users",{...userInfo,addtime,status:1}).catch(err=>{
			console.error(err)
		})
	},
	  //用户播放历史
		getPlayHistory() {
			var history = wx.getStorageSync("history") || [];
			this.setData({
				history,
			});
		},
		//删除播放历史
		deleteHistory(e) {
			wx.showModal({
				title: "提示",
				content: "您确定要删除这条记录？",
				showCancel: true,
				success: (res) => {
					if (res.confirm) {
						//删除图书
						var index = e.target.id;
						console.log(index);
						var history = wx.getStorageSync("history") || [];
						history.splice(index, 1);
						wx.setStorageSync("history", history);
						this.setData({
							history,
						});
					}
				},
			});
		},
		toIndex(){
			wx.reLaunch({
				url: '/pages/index/index',
			})
		}
});
